package com.fqdf.framework.android.service.downloadservice.helper;


import com.fqdf.framework.android.net.HttpStatus;
import com.fqdf.framework.android.net.client.DFOkHttp;
import com.fqdf.framework.android.service.downloadservice.DownloadConstans;
import com.fqdf.framework.android.util.CheckLogicUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * @author 张枭
 * @version V1.0
 * @date 2017/5/3
 * @desc
 */
public class OkHttpDownloadHelper extends DownloadHelper {

    @Override
    DownloadConstans.RESULT downloadFile(String url, File file) {
        if (CheckLogicUtil.isEmpty(url) || file == null) {
            return DownloadConstans.RESULT.PARAMS;
        }

        BufferedSource bufferedSource = null;
        BufferedSink bufferedSink = null;
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Request request = new Request.Builder().url(url).build();
            Response response = DFOkHttp.getInstance().getOkhttpClient().newCall(request).execute();

            if (response.code() == HttpStatus.HTTP_OK) {

                ResponseBody body = response.body();
                bufferedSource = body.source();
                bufferedSink = Okio.buffer(Okio.sink(file));
                // 注释掉的内容主要为计算相关下载进度，暂时用不到
//                long contentLength = body.contentLength();
                Buffer sinkBuffer = bufferedSink.buffer();
//                long totalBytesRead = 0;
                int bufferSize = 2 * 1024;
                long bytesRead;
                while ((bytesRead = bufferedSource.read(sinkBuffer, bufferSize)) != -1) {
                    sinkBuffer.emit();
//                    totalBytesRead += bytesRead;
//                    int progress = (int) ((totalBytesRead * 100) / contentLength);
                }
                bufferedSink.flush();

                return DownloadConstans.RESULT.SUCCESS;
            } else {
                return DownloadConstans.RESULT.FAILURE;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        } catch (IOException e) {
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        } catch (Exception e) {
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        } finally {
            Util.closeQuietly(bufferedSink);
            Util.closeQuietly(bufferedSource);
        }
    }
}
